package com.gaohe.controller;

import com.gaohe.common.R;
import com.gaohe.utils.MinioUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {
    @Autowired
    MinioUtils minioUtils;

    @Value("${minio.bucketName}")
    String bucketName;
//    文件上传
    @PostMapping("upload")
    private R upload(MultipartFile file)
    {
        log.info("file{}",file);
        String originFilename = file.getOriginalFilename();

        int indexOf = originFilename.lastIndexOf(".");
        String sub = originFilename.substring(indexOf);//.png

        String name = UUID.randomUUID().toString()+sub;
        String type = file.getContentType();
//        临时文件上传到minio
        minioUtils.uploadFile(bucketName,file,name,type);
//        上传路径或者名称，这里上传的是名称
        return R.success(name);
    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse httpServletResponse) throws IOException {
//        从云端库获取图片,minion自动关闭
        InputStream in = minioUtils.getObject(bucketName,name);
//        servlet也会自动关闭
        ServletOutputStream out = httpServletResponse.getOutputStream();
        int len = -1;
        byte[]bytes = new byte[1024];
        while((len = in.read(bytes)) != -1)
        {
            out.write(bytes,0,len);
            out.flush();
        }

    }

}
